package com.shortvedio.media.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shortvedio.media.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;


@RestController
@Slf4j
public class CallBackController {

    @Autowired
    MediaService mediaService;

    @ResponseBody
    @RequestMapping("checkFileCallBack")//视频鉴黄等的回调
    public void checkFileCallBack(@RequestBody JSONObject param) {
        //判断文件是否被禁用
        JSONArray items = param.getJSONArray("items");
        JSONObject jsonObject = items.getJSONObject(0);
        JSONObject result = jsonObject.getJSONObject("result");
        String disable = result.getString("disable");
        if (disable.equals("true")){
            //获取到文件名
            String inputKey = param.getString("inputKey");
            mediaService.deleteFile(inputKey);
        }
    }


    @PostMapping(value="/add_tesk_callback")//视频转码--视频截图的回调处理
    public void AddTeskCallback(HttpServletRequest request, HttpServletResponse response){
        try {
            // 接收七牛回调过来的内容
            String line = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            // 设置返回给七牛的数据
            JSONObject checkResult = JSON.parseObject(sb.toString());
            //获取到key
            String inputkey = checkResult.getString("inputKey");
            //截取名称 存入数据库中
            String addTeskKey = inputkey.substring(0,inputkey.lastIndexOf("."));
            //添加到任务队列中
            mediaService.AddTeskVedio(addTeskKey);
            //删除文件  不等于MP4时
            if (!inputkey.substring(inputkey.lastIndexOf(".")).equals(".mp4")){
                mediaService.deleteFile(inputkey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
